﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using log4net;

public partial class viewImage : System.Web.UI.Page
{
    //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(viewImage).Name);

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                Loads();
            }
        }
        catch (Exception ex)
        {
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    private void Loads()
    {  
        string id = string.Empty;

         if (Request.QueryString["id"] != null)
         {
             id = Request.QueryString["id"].ToString();
         }
         if (!Utils.IsGuid(id))
         {
             return;
         }

         hdnId.Value = id;
         string strQuery = "SELECT [EntryTime],[ExitTime] FROM EntryExit WHERE ID=@Id";

         SqlParameter parm = new SqlParameter("@Id", new Guid(id));


         try
         {
             using (SqlDataReader dr = SqlHelper.ExecuteReader(CommandType.Text, strQuery, parm))
             {
                 if (dr.Read())
                 {
                     if (SqlHelper.CheckDateNull(dr["EntryTime"]) != null)
                     {
                         ltrTimeIn.Text = DateTime.Parse(SqlHelper.CheckDateNull(dr["EntryTime"]).ToString()).ToString("dd/MM/yyyy HH:mm");
                     }
                     else
                     {
                         ltrTimeIn.Text = String.Empty;
                     }

                     if (SqlHelper.CheckDateNull(dr["ExitTime"]) != null)
                     {
                         ltrTimeOut.Text = DateTime.Parse(SqlHelper.CheckDateNull(dr["ExitTime"]).ToString()).ToString("dd/MM/yyyy HH:mm");
                     }
                     else
                     {
                         ltrTimeOut.Text = String.Empty;
                     }                     
                     btnDisable.Visible = (SqlHelper.CheckDateNull(dr["ExitTime"]) == null);
                 }
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }

         imgFrontEntry.ImageUrl = "includes/EntryFront.aspx?id=" + id;
         imgRearEntry.ImageUrl = "includes/EntryRear.aspx?id=" + id;
         imgFrontExit.ImageUrl = "includes/ExitFront.aspx?id=" + id;
         imgRearExit.ImageUrl = "includes/ExitRear.aspx?id=" + id;
    }

    private string GetPlateNoById(Guid id)
    {
        string sql = @"SELECT [PlateNumber] FROM EntryExit
                          WHERE [ID]=@Id";
        SqlParameter parm = new SqlParameter("@Id", SqlDbType.UniqueIdentifier);
        parm.Value = id;
        object obj= SqlHelper.ExecuteScalar(CommandType.Text, sql, parm);
        if (obj == null) return String.Empty;
        return obj.ToString();
    }

    private string GetCardIdById(Guid id)
    {
        string sql = @"SELECT [CardID] FROM EntryExit
                          WHERE [ID]=@Id";
        SqlParameter parm = new SqlParameter("@Id", SqlDbType.UniqueIdentifier);
        parm.Value = id;
        object obj = SqlHelper.ExecuteScalar(CommandType.Text, sql, parm);
        if (obj == null) return String.Empty;
        return obj.ToString();
    }

    

    private int GetPrice(Guid id)
    {
        string sql = @"SELECT Count([ID])
                          FROM [MonthCard]
                          WHERE Active=1 AND dbo.ufn_StripCharacters(PlateNumber, '^a-z0-9')=dbo.ufn_StripCharacters(@PlateNumber, '^a-z0-9')";
        SqlParameter parm = new SqlParameter("@PlateNumber", SqlDbType.NVarChar, 50);
        parm.Value = GetPlateNoById(id);
        object obj = SqlHelper.ExecuteScalar(CommandType.Text, sql, parm);
        if (obj != null && SqlHelper.CheckIntNull(obj) > 0)
        {
            return 0;
        }

        sql = @"SELECT Price FROM CardPrice
            WHERE CardTypeID=(SELECT CardTypeID FROM Card WHERE CardID =@CardID)";
        parm = new SqlParameter("CardID", SqlDbType.NVarChar, 50);
        parm.Value = GetCardIdById(id);
        obj = SqlHelper.ExecuteScalar(CommandType.Text, sql, parm);
        if (obj == null) return 0;
        return SqlHelper.CheckIntNull(obj);
    }       

    protected void btnDisable_Click(object sender, EventArgs e)
    {
        try
        {
            if (hdnId.Value == null || !Utils.IsGuid(hdnId.Value))
            {
                return;
            }

            if (Session["Employee"] == null)
            {
                return;
            }
            Employee emp = (Employee)Session["Employee"];

            string sql = @"UPDATE [Card] 
                            SET [Active]=0, LastUser=@LastUser 
                            WHERE CardID=(SELECT CardID FROM EntryExit WHERE [ID]=@Id)";
            SqlParameter[] parms = new SqlParameter[]{
                        new SqlParameter("@Id", new Guid(hdnId.Value)),
                        new SqlParameter("@LastUser", emp.Id)
                    };
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, parms);
            sql = @"UPDATE EntryExit 
                    SET ExitTime=GETDATE(), 
                    Price=@Price, 
                    EntryPlate=PlateNumber,
                    ExitUpdateUser=@ExitUpdateUser
                    WHERE [Id]=@Id";
            parms = new SqlParameter[]{
                        new SqlParameter("@Id", new Guid(hdnId.Value)),                        
                        new SqlParameter("@Price", GetPrice(new Guid(hdnId.Value))),
                        new SqlParameter("@ExitUpdateUser", emp.Id)
                    };
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, parms);
//            Response.Write(@"<script>
//                            alert('Vô hiệu hóa thẻ xe bị mất thành công.');
//                            window.close();
//                            </script>");
            Response.Write(@"<script>                            
                            window.close();
                            </script>");
        }
        catch (Exception ex)
        {
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
}